<?php 
 
namespace App\Http\Controllers\Admin; 
 
use App\Http\Controllers\Controller; 
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use App\Http\Requests\RoleRequest;
use App\Role;
use App\Permission;
use Auth;

class RoleController extends Controller 
{ 
    /** 
     * Create a new controller instance. 
     * 
     * @return void 
     */ 

    // 
    const model="PersonnelManagement";
    //
    public function __construct(){
        $this->model=self::model;

    }

    public function index() 
    { 
        $role=Role::sortId('desc')->paginate(15);
        return view('admin.role.index',['model'=>$this->model,'role'=>$role]);
    }

    public function create() 
    { 
        $permission=Permission::get();
        return view('admin.role.create',['model'=>$this->model,'permission'=>$permission]);
    }

    public function store(RoleRequest $request){
        $permission=$request->input('permission');
        
        $data=$request->intersect('name','display_name','description');

        try {
            $role=Role::create($data);
            $role->perms()->sync($permission);
        } catch (Exception $e) {    
        return   parent::error('error');
        }
        return parent::success('success',route('admin.role.index'));
    }

    public function edit($id){
        $role=Role::with('perms')->find($id);
        $permission=Permission::get();
        return view('admin.role.edit',['model'=>$this->model,'role'=>$role,'permission'=>$permission]);
    }

    public function update(Request $request){
        $permission=$request->input('permission');
        $id=$request->input('id');
        $data=$request->intersect('name','display_name','description');

        try {
            $role=Role::where('id',$id)->update($data);
            $role=Role::find($id);
            $role->perms()->sync($permission);
        } catch (Exception $e) {    
        return   parent::error('error');
        }
        return parent::success('success',route('admin.role.index'));
    }

    public function del($id){

        try {
            Role::destroy($id);
        } catch (Exception $e) {    
            return   parent::error('error');
        }

        return parent::success('success',route('admin.role.index'));

    }
}
